package com.panshi.utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", filterName = "myFilter")
public class MyFilter implements Filter {

    //哪些后台服务需要进行token验证（需要登录后才能访问）
    private String[] urls = new String[] {"qa/*","upload","messages","deleteUserDynamic","deleteUserCollect",
    "addComment","articlePublish","article/publish","askQuestions","ask/questions"};
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //获取session
        HttpServletRequest httpRequest=(HttpServletRequest)request;
        HttpServletResponse httpResponse=(HttpServletResponse)response;
        //获取访问的Origin
        String myOrigin = httpRequest.getHeader("Origin");
        if (myOrigin != null) {
            //设置跨域请求
            httpResponse.setHeader("Access-Control-Allow-Origin", myOrigin);
            httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,	PUT");
            httpResponse.setHeader("Access-Control-Max-Age", "3600");
            httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,Authorization,AuthToken");
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("XDomainRequestAllowed","1");

        }
        //请求地址
        String uri = httpRequest.getRequestURI();
        //判断是否属于需要过滤的资源
        boolean pass = false;
        if(urls != null){
            for (int i = 0; i < urls.length; i++) {
                if (uri.indexOf(urls[i])>-1){
                    pass = true;
                    break;
                }else if(uri.indexOf("personal")>-1){
                    pass = true;
                    break;
                }
            }
        }
        //session对象
        HttpSession session = httpRequest.getSession();

        if (pass == true) {//需要登录之后才能访问
            Object obj = session.getAttribute(session.getId());
            if(obj==null){
               httpResponse.sendRedirect("/login");
            }else{
                //正常请求
                chain.doFilter(httpRequest, httpResponse);
            }
        } else {
            //正常请求
            chain.doFilter(httpRequest, httpResponse);
        }
    }

}
